<template>
	<div class="page" style="text-align: left;" @click="closePop">
		<div class="top">
			<div style="float:left;"><span @click="goBack" class="goback">设备管理</span>　|　<span>配置虚拟设备</span>　|　<span>{{deviceData.equip_name}}</span></div>
			<el-button type="primary" size="small" id="goback" @click="goBack">返回</el-button>
		</div>
	    <div class="btnBox">
		   <el-button @click="addSensor" style="vertical-align: middle;" type="primary" size="small">新增虚拟数据点</el-button>
		   <el-button @click="examConnect" type="primary" size="small" style="vertical-align: middle;"   v-if="deviceData.equip_state==1 && !isExam && domains.length">设备调试
		   </el-button>
		   <el-button @click="cancelConnect" type="primary" size="small" style="vertical-align: middle;" v-if="deviceData.equip_state==1 && isExam && domains.length">关闭调试
		   </el-button>
	       <!-- <el-button type="success" size="small" style="vertical-align: middle;" @click="updateSensor">保存</el-button> -->
	    </div>
		<div class="virSensorList">
			<div class="virSensorHead">
					<span class="inpu_4" style="width:1rem;height:0.8rem;">图标</span>
					<span class="inpu_4" style="width:2.8rem;margin-right:0.4rem;">名称</span>
					<span class="inpu_4" v-if="isExam" style="width:1rem;margin-right:0.45rem;color:deepskyblue;border-bottom:1px solid deepskyblue;">调试值</span>
					<span class="inpu_4" style="width:1.2rem;margin-right:0.4rem;">地址</span>
					<div class="inpu_4" style="width:1.9rem;">
						<span>存储</span>
						<el-tooltip placement="top" effect="light">
						  <div slot="content" style="line-height:0.4rem;color:red;">注意事项:<br/>如果选择不存储，该数据点将没有历史数据和历史曲线！</div>
						  <span class="sortIcon" style="color:red;">!</span>
						</el-tooltip>
					</div>
					<div class="inpu_4" style="width:2.1rem;">
						<span>单位</span>
						<el-tooltip placement="top" effect="light">
						  <div slot="content" style="line-height:0.4rem;color:red;">注意事项:<br/>为了体现专业化和减少占位长度以方便显示，尤其是手机端的显示，单位请使用数学写法，勿使用汉字！</div>
						  <span class="sortIcon" style="color:red;">!</span>
						</el-tooltip>
					</div>
					<span class="inpu_4" style="width:1.1rem">小数位</span>
					<span class="inpu_4" style="width:3.8rem">数据属性</span>
					<span class="inpu_4" style="width:260px;">计算公式</span>
					<span class="inpu_4" style="width:1.7rem;">排序</span>
					<!-- <div class="inpu_4 sort" style="width:1.8rem;">
						<span>排序</span>
						<el-tooltip placement="top" effect="light">
						  <div slot="content" style="line-height:0.4rem;">支持的排序写法:<br/>1.数字:如:0,1,2,3,...;<br/>2.小写字母+数字:如:a1,a2,a3,...,b1,b2,b3,...</div>
						  <span class="sortIcon">?</span>
						</el-tooltip>
					</div> -->
					<!-- <span  class="inpu_4" :style="{'width':domains.length>1?'1.7rem':'0.8rem'}">操作</span> -->
					<span  class="inpu_4" style="width:1.7rem;">操作</span>
				</div>
				<div v-if="domains.length" class="triBox">
					<div v-for="(item, index) in domains" class="oneSensor" :key="index">
						<el-popover placement="top" width="210" style="z-index:9999;height:210px;line-height:70px;" trigger="manual"
						 v-model="item.visible">
							<img v-for="(i) in 18" :key="i" :src="baseurl+'static/images/icon/icon'+i+'.png'" class="thumb" style="margin-left:0.27rem;margin-bottom:0.2rem;"
							 :id="i" @click="chooseIcon(i,item)" />
							<el-button slot="reference" class="iconbtn" @click="getIndex(index)"><img v-if="item.icon" :id="index" :src="baseurl+item.icon"
								 class="thumb" title="点击更换" style="width:0.65rem;height:0.65rem;"/></el-button>
						</el-popover>
						<!-- <img :src="baseurl+item.icon" style="width:0.65rem;height:0.65rem;margin-left:0.1rem;margin-right:0.1rem;" /> -->
						<span class="inpu_2" @click="updateOne(index,item,'sensor_name','名称')" title="点击修改" style="width:3.5rem;cursor:pointer;"  placeholder="数据点名称">{{item.sensor_name}}</span>
						<span class="inpu_2 over noWrite" title="只读变量" v-if="isExam" :style="{'color':(item.value=='bad' || item.value=='error')?'red':'#111'}" >{{item.value}}</span>
						<span class="inpu_2" style="width:1.8rem;" title="自动生成,不可修改">{{item.data_key}}</span>
						<span class="inpu_2" @click="updateOne(index,item,'save_type','存储')" title="点击修改" style="width:2.4rem;cursor:pointer;">{{item.save_type}}</span>
						<span class="inpu_2" @click="updateOne(index,item,'unit','单位')" title="点击修改" style="width:1.9rem;cursor:pointer;">{{item.unit}}</span>
						<span class="inpu_2" @click="updateOne(index,item,'decimals','小数位')" title="点击修改" style="width:1.6rem;cursor:pointer;">{{item.decimals}}</span>
						<span class="inpu_2" @click="updateOne(index,item,'report_type','数据属性')" title="点击修改" style="width:3.5rem;cursor:pointer;">{{item.report_type | reportTypeFilter}}</span>
						<el-popover
						    placement="top"
						    :title="item.sensor_name+' | 计算公式'"
						    width="600"
						    trigger="hover"
							close-delay="0"
						    :content="item.formula">
						    <div  class="formulaBox"  slot="reference" title="点击可编辑" @click="editFormula(item)">
						       <span  class="formulaText over"  >{{item.formula}}</span>
						       <span  class="formulaEdit"   ><i class="el-icon-edit" style="font-size:0.35rem;cursor: pointer;color:deepskyblue;" ></i></span>
						    </div>
						    <!-- <div  class="formulaBox"  slot="reference">
							   <span  class="formulaText over"  @click="fillString(item)">{{item.formula}}</span>
							   <span  class="formulaEdit"   @click="editFormula(item)"><i class="el-icon-edit" style="font-size:0.35rem;cursor: pointer;color:deepskyblue;" ></i></span>
							</div> -->
						</el-popover>
						<span class="inpu_2" @click="updateOne(index,item,'list_order','排序')" title="点击修改" style="width:1.2rem;cursor:pointer;">{{item.list_order}}</span>
						<el-button :disabled="domains.length==1" style="vertical-align:top;margin:2px 0 0 0.1rem;padding:6px 10px;" @click.prevent="sureDeleteSensor(item)" type="danger" size="mini" >删除</el-button>
						<el-button @click.prevent="showUpdate(index,$event,item.id)" type="primary"  size="mini"
							style="vertical-align:top;padding:6px 10px;margin:2px 0 0 -0.1rem;">编辑</el-button>
						<!-- <el-button v-else @click.prevent="showUpdate(index,$event,item.id)" type="primary"  size="mini"
							style="vertical-align:top;padding:6px 10px;margin:2px 0 0 0.2rem;">编辑</el-button> -->
					</div>
				</div>
				<div v-else class="triBox" style="font-size:0.35rem;color:#ccc;text-align: center;">
					暂无数据点
				</div>
		</div>
		<el-dialog :visible="formulaVisible"  :width="win.screen.width>=1600?'46%':'66%'"  :show-close="false" append-to-body top="200px" class="dial">
			<div class="toptit">
				<span>计算公式编辑</span>
				<span style="float:right;cursor: pointer;" @click="formulaVisible=false">关闭</span>
			</div>
			<el-input class="editFormula" type="textarea" style="width:100%;margin-top:0.25rem;" v-model="editForm.formula" :autosize="{minRows:5,maxRows:20}"></el-input>
			<div style="text-align:right;margin-top:0.4rem;">
			    <el-button size="small" @click="formulaVisible=false">取 消</el-button>
			    <el-button type="primary" size="small" @click="updateSensor">确 定</el-button>
			</div>
			<div class="rightBox"   :class="!drawerShow?'zeroWidth':''">
				<div class="rightHead">
					<span style="float:left;">变量列表</span>
					<el-button v-show="reSet" style="float:right;vertical-align:middle;margin-top:4px;" size="mini" @click="reSetString">清空标记</el-button>
				</div>
				<div class="sensorTree">
					<el-input
					  style="width:98%;display:block;margin:0 auto;"
					  placeholder="输入关键字进行过滤"
					  v-model="filterText">
					</el-input>
					<el-tree
					  style="margin-top:0.1rem;"
					  class="filter-tree"
					  :data="sensorTree"
					  @node-click="getSensorString"
					  default-expand-all
					  :filter-node-method="filterNode"
					  ref="tree">
					</el-tree>
				</div>
			</div>
		</el-dialog>
		<!-- <FormulaCreater
		    style="width:22%"
		   :drawerShow="drawerShow"
		   :sensorTree="sensorTree"
		   :getSensorString="getSensorString"
		   appType="device"
		></FormulaCreater> -->
		<el-dialog :visible.sync="addFormVisible" v-el-dialog-drag v-el-dialog-drag-width :width="win.screen.width>1600?'60%':'75%'" append-to-body
			:show-close="close" :close-on-click-modal="false" top="150px" class="dial">
			<div class="toptit">
				<span>新增虚拟数据点</span>
				<span style="float:right;cursor: pointer;" @click="addFormVisible=false">关闭</span>
			</div>
			<el-form :model="addForm" style="text-align: left;" inline>
				<div style="font-size:0.3rem;font-weight: 600;width:100%;margin:0.2rem 0 0.3rem 0;">数据点参数：<span
							style="color:red;font-weight:normal;font-size:0.25rem;">已默认部分参数；名称必须唯一,用于显示和选择,建议与实际语义化；</span>
					<!-- <el-button size="mini" v-if="addForm.is_virtual==1 && !drawerShow" style="margin-left:0.3rem;" @click="varStringHelp('add')">打开公式生成器</el-button> -->
					<!-- <el-button size="mini" v-if="addForm.is_virtual==1 && drawerShow" style="margin-left:0.3rem;"  @click="varStringHelp('add')">关闭公式生成器</el-button> -->
					<el-button size="mini" style="margin-left:0.3rem;" @click="formulaInfoVisible=true">计算公式说明</el-button>	
				</div>
				<el-form-item label="名称:" class="formline_2"  :label-width="formLabelWidth">
					<el-input class="inpu_3 over" v-model="addForm.sensor_name"  placeholder="数据点名称"></el-input>
				</el-form-item>
				<el-form-item class="formline_2" label="小数位:" :label-width="formLabelWidth">
					<el-select :disabled="addForm.show_type>2" v-model="addForm.decimals" class="inpu_3" @change="changeAddDecimal(addForm.decimals,addForm.magnification)">
						<el-option v-for="item in points" :key="item.value" :value="item.value" :label="item.label">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="formline_2" label="数据属性:" :label-width="formLabelWidth">
					<el-select v-model="addForm.report_type" class="inpu_3">
						<el-option v-for="item in reportTypes" :key="item.value" :value="item.value"
							:label="item.label">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="formline_2" label="单位:" :label-width="formLabelWidth">
					<el-input :disabled="addForm.show_type>2" class="inpu_3" v-model="addForm.unit"
						:placeholder="addForm.show_type<3?'单位，可为空':'非数值，禁用'"></el-input>
				</el-form-item>
				<el-form-item class="formline_2" label="数据存储:" :label-width="formLabelWidth">
					<el-select v-model="addForm.save_type" placeholder="是否存储" class="inpu_3">
						<el-option v-for="item in saves" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item  class="formline_2" label="排序:" :label-width="formLabelWidth">
					<el-input class="inpu_3" v-model="addForm.list_order" placeholder="排序"></el-input>
				</el-form-item>
				<!-- <el-form-item  class="formline_2" style="height:1rem;line-height:1rem;margin-top:0.2rem;" label="图标:"
					:label-width="formLabelWidth">
					<el-popover placement="top" width="240"
							style="display:line-block;height:3.5rem;line-height:1rem;vertical-align: middle;margin-top:-0.5rem;margin-left:0.1rem;"
							trigger="click" >
						<img v-for="(i) in 18" :key="i" :src="baseurl+'static/images/icon/icon'+i+'.png'"
							class="thumb" style="margin-left:0.27rem;margin-bottom: 0.2rem;" :id="i"
							@click="chooseIcon" />
						<el-button slot="reference" class="iconbtn">
							<img :src="baseurl+addForm.icon" class="thumb" />
						</el-button>
					</el-popover>
					<span style="float:right;width:auto;vertical-align: middle;margin:0.1rem 0.2rem;">点击图标切换</span>
				</el-form-item> -->
				<!-- <el-form-item  v-if="addForm.is_virtual==1" class="formline_2" style="width:100%;" label="计算公式:" :label-width="formLabelWidth">
					<el-input  class="inpu_3"  style="width:18.25rem;"  :title="addForm.formula" v-model="addForm.formula"   @dblclick.native="fillString('add')"
						placeholder="双击自动填入(或替换)右侧计算公式"></el-input>
				</el-form-item> -->
				<el-form-item   class="formline_2" style="width:100%;" label="计算公式:" :label-width="formLabelWidth">
					<el-input  class="inpu_3"  style="width:18.25rem;" type="textarea" :autosize="{minRows:1.5,maxRows:5}" resize="none" :title="addForm.formula" v-model="addForm.formula"   
						placeholder="先点击变量,后加入运算符"></el-input>
				</el-form-item>
			</el-form>
			<div style="text-align: right;margin-top:1.6rem;">
				<el-button  size="small" @click="addFormVisible=false">取 消</el-button>
				<el-button type="primary" size="small" @click="addHappen(addForm.is_virtual)">确 定</el-button>
			</div>
			<!-- <FormulaCreater
			   style="width:18%;"
			   :drawerShow="drawerShow"
			   :sensorTree="sensorTree"
			></FormulaCreater> -->
			<div class="rightBox"  :class="!drawerShow?'zeroWidth':''">
				<div class="rightHead">
					<span style="float:left;">变量列表</span>
					<el-button  v-show="reSet" style="float:right;vertical-align:middle;margin-top:4px;" size="mini" @click="reSetString">清空标记</el-button>
				</div>
				<div class="sensorTree">
					<el-input
					  style="width:98%;display:block;margin:0 auto;"
					  placeholder="输入关键字进行过滤"
					  v-model="filterText">
					</el-input>
					
					<el-tree
					  style="margin-top:0.1rem;"
					  class="filter-tree"
					  :data="sensorTree"
					  @node-click="getSensorString"
					  default-expand-all
					  :filter-node-method="filterNode"
					  ref="tree">
					</el-tree>
				</div>
				<!-- <div class="stringBox">
					<div>
						<span>计算公式：<span>先点击数据点，后插入运算符</span></span>
						<el-button size="mini" v-if="sensorString" @click="reSetString" style="float: right;vertical-align: middle;">清空</el-button>
					</div>
					<el-input  type="textarea" ref="sensorString" v-model="sensorString" :autosize="{minRows:7,maxRows:20}"></el-input>
				</div> -->
			</div>
		</el-dialog>
		<el-dialog :visible="editFormVisible"  v-el-dialog-drag v-el-dialog-drag-width :width="win.screen.width>1600?'60%':'70%'" append-to-body class="dial"
			:show-close="close" top="150px">
			<div class="toptit">
				<span>编辑虚拟数据点</span>
				<span style="float:right;cursor: pointer;" @click="editFormVisible=false">关闭</span>
			</div>
			<el-form :model="editForm" style="text-align:left;" inline>
				<div style="font-size:0.3rem;font-weight: 600;width:100%;margin:0.2rem 0 0.3rem 0;">数据点参数：<span
							style="color:red;font-weight:normal;font-size:0.25rem;">名称必须唯一,用于显示和选择,建议与实际语义化；</span>
					<!-- <el-button size="mini" v-if="addForm.is_virtual==1 && !drawerShow" style="margin-left:0.3rem;" @click="varStringHelp('add')">打开公式生成器</el-button> -->
					<!-- <el-button size="mini" v-if="addForm.is_virtual==1 && drawerShow" style="margin-left:0.3rem;"  @click="varStringHelp('add')">关闭公式生成器</el-button> -->
					<el-button size="mini" style="margin-left:0.3rem;" @click="formulaInfoVisible=true">计算公式说明</el-button>	
				</div>
				<el-form-item label="名称:" class="formline_2" :label-width="formLabelWidth">
					<el-input class="inpu_3 over"  v-model="editForm.sensor_name" placeholder="数据点名称"></el-input>
				</el-form-item>
				<el-form-item class="formline_2"   label="小数位:" :label-width="formLabelWidth">
					<el-select :disabled="editForm.show_type>2" v-model="editForm.decimals"
						 class="inpu_3">
						<el-option v-for="item in points" :key="item.value" :value="item.value" :label="item.label">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="formline_2"   label="数据属性:" :label-width="formLabelWidth">
					<el-select v-model="editForm.report_type" class="inpu_3">
						<el-option v-for="item in reportTypes" :key="item.value" :value="item.value"
							:label="item.label">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="formline_2" label="单位:" :label-width="formLabelWidth">
					<el-input :disabled="editForm.show_type>2" class="inpu_3" v-model="editForm.unit"
						:placeholder="editForm.show_type>2?'非数值,禁用':'单位,可无'"></el-input>
				</el-form-item>
				<el-form-item class="formline_2" label="数据存储:" :label-width="formLabelWidth">
					<el-select v-model="editForm.save_type" placeholder="是否存储" class="inpu_3">
						<el-option v-for="item in saves" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item  class="formline_2" label="排序:" :label-width="formLabelWidth">
					<el-input class="inpu_3" v-model="editForm.list_order" placeholder="排序"></el-input>
				</el-form-item>
				<el-form-item   class="formline_2" style="width:100%;" label="计算公式:" :label-width="formLabelWidth">
					<el-input  class="inpu_3" style="width:18.25rem;"  :title="editForm.formula" v-model="editForm.formula" type="textarea" :autosize="{minRows:1.5,maxRows:5}" resize="none" 
						placeholder="先点击变量,后加入运算符"></el-input>
				</el-form-item>
				<!-- <el-form-item  class="formline_2" style="height:1rem;line-height:1rem;margin-top:0.1rem;" label="图标:"
					:label-width="formLabelWidth">
					<el-popover placement="top" width="240"
						style="height:3.5rem;line-height:1rem;vertical-align: middle;margin-top:-0.5rem;margin-left:0.1rem;"
						trigger="click">
						<img v-for="(i) in 18" :key="i" :src="baseurl+'static/images/icon/icon'+i+'.png'"
							class="thumb" style="margin-left:0.27rem;margin-bottom: 0.2rem;" :id="i"
							@click="chooseIcon_2" />
						<el-button slot="reference" class="iconbtn"><img :src="baseurl+editForm.icon"
								class="thumb" /></el-button>
					</el-popover>
					<span style="float:right;width:auto;vertical-align: middle;margin:0.1rem 0.2rem;">点击图标切换</span>
				</el-form-item> -->
			</el-form>
		    <div style="text-align: right;margin-top:1.6rem;">
				<el-button  size="small" @click="editFormVisible=false">取 消</el-button>
				<el-button type="primary" size="small" @click="updateSensor">确 定</el-button>
			</div>
			
			<div class="rightBox"   :class="!drawerShow?'zeroWidth':''">
				<div class="rightHead">
					<span style="float:left;">变量列表</span>
					<el-button v-show="reSet" style="float:right;vertical-align:middle;margin-top:4px;" size="mini" @click="reSetString">清空标记</el-button>
				</div>
				<div class="sensorTree">
					<el-input
					  style="width:98%;display:block;margin:0 auto;"
					  placeholder="输入关键字进行过滤"
					  v-model="filterText">
					</el-input>
					<el-tree
					  style="margin-top:0.1rem;"
					  class="filter-tree"
					  :data="sensorTree"
					  @node-click="getSensorString"
					  default-expand-all
					  :filter-node-method="filterNode"
					  ref="tree">
					</el-tree>
				</div>
			</div>
		</el-dialog>
		<el-dialog :visible="oneUpdateVisible" v-el-dialog-drag v-el-dialog-drag-width :width="win.screen.width>1600?'25%':'35%'" append-to-body class="dial"
			:show-close="close" top="200px">
			<div class="toptit">
				<span>{{whatName}} | 属性修改</span>
				<span style="float:right;cursor: pointer;" @click="oneUpdateVisible=false">关闭</span>
			</div>
			<el-form :model="editForm" style="text-align:left;margin-top:0.3rem;" block>
				<el-form-item v-show="whichOne=='sensor_name'" label="名称:" :label-width="formLabelWidth">
					<el-input class="inpu_3 over" style="vertical-align:top;" v-model="editForm.sensor_name" placeholder="数据点名称"></el-input>
				</el-form-item>
				<el-form-item v-show="whichOne=='decimals'" :class="editForm.is_virtual==0?'equipArg':''" label="小数位:" :label-width="formLabelWidth">
					<el-select :disabled="editForm.show_type>2" v-model="editForm.decimals"
						@change="changeEditDecimal(editForm.decimals,editForm.magnification)" :placeholder="editForm.show_type>2?'非数值,禁用':''"
						class="inpu_3" style="vertical-align:top;">
						<el-option v-for="item in points" :key="item.value" :value="item.value" :label="item.label">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-show="whichOne=='report_type'" :class="editForm.is_virtual==0?'equipArg':''" label="数据属性:" :label-width="formLabelWidth">
					<el-select v-model="editForm.report_type" class="inpu_3" style="vertical-align:top;">
						<el-option v-for="item in reportTypes" :key="item.value" :value="item.value"
							:label="item.label">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-show="whichOne=='save_type'" label="数据存储:" :label-width="formLabelWidth">
					<el-select v-model="editForm.save_type" placeholder="是否存储" class="inpu_3" style="vertical-align:top;">
						<el-option v-for="item in saves" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-show="whichOne=='unit'" label="单位:" :label-width="formLabelWidth">
					<el-input :disabled="editForm.show_type>2" class="inpu_3" style="vertical-align:top;" v-model="editForm.unit"
						:placeholder="editForm.show_type>2?'非数值,禁用':'单位,可无'"></el-input>
				</el-form-item>
				<el-form-item v-show="whichOne=='list_order'" label="排序:" :label-width="formLabelWidth">
					<el-input class="inpu_3" style="vertical-align:top;" v-model="editForm.list_order" placeholder="排序"></el-input>
				</el-form-item>
			</el-form>
			<div style="text-align: right;margin-top:0.4rem;">
				<el-button  size="small" @click="oneUpdateVisible=false">取 消</el-button>
				<el-button type="primary" size="small" @click="updateSensor">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog :visible="formulaInfoVisible"  :width="win.screen.width>=1600?'48%':'68%'"  :show-close="false" append-to-body top="200px" class="dial">
			<div class="toptit">
				<span>计算公式说明</span>
				<span style="float:right;cursor: pointer;" @click="formulaInfoVisible=false">关闭</span>
			</div>
			<div class="infocontent" style="margin-top:0.2rem;">
				 <!-- <h2 style="width:100%;text-align: center;margin-top:0.2rem;"></h2><br> -->
				<p>
				 1.目前只支持的+,-,*(乘),/(除)四则运算及其组合,支持跨设备运算；<br>
				 2.计算公式请全部使用英文字符书写；<br>
				 3.计算公式基本组成：变量地址 运算符 其他变量地址或数值；<br>
				 4.变量地址模板：$product[设备编码]["devices"][子设备ID]["variables"][数据点地址],示例：$product["330821080454202"]["devices"]["Local"]["variables"]["0x00001"]；<br>
				 <!-- 5.建议使用公式生成器生成公式，生成后，点击左侧计算公式输入框自动填入；<br> -->
				 5.点击变量自动生成变量地址，可先点击完所有变量，然后插入运算符(变量地址之间($符之前)的留空处)，也可顺序点击，顺序输入运算符；<br>
				 6.需要改变计算公式的运算优先级时，请使用英文小括号"()",不支持中括号和大括号；<br>
				 7.公式示例：($product["330821080454202"]["devices"]["Local"]["variables"]["0x00001"] + 3) + $product["330821080454201"]["devices"]["Slave2"]["variables"]["4x00001"] * 100；
				</p>
			</div>
		</el-dialog>
		
	</div>
</template>

<script>
    import {
        reportTypes,
        saves,
        options,
        points
    } from '@/common.js';
	//import FormulaCreater from '../templates/FormulaCreater.vue';
	//import FormulaInfo from '../templates/FormulaInfo.vue';
    export default {
        name: 'setVirtualDevice',
        data() {
            return {
				win:window,
				close:false,
				drawerShow:true,
				reSet:false,
				filterText:'',
				sensorString:'',
				sensorTree:[],
				deviceData:{},
				sibling:[],
				oper:'add',
				whichOne:'',
				whatName:'',
				whatText:'',
				addForm: {
					equip_id:0,
					sensor_name: '',
					show_type: 1,
					save_type: 2, //1存储，2不存储，3变化存储
					data_key: '',
					unit: '',
					report_type: 0,
					decimals: 0,
					list_order: 0,
					magnification: 1,
					value_offset: 0,
					threshold:0,
					icon: 'static/images/icon/icon1.png',
					is_virtual:1,
					formula:''
				},
				editForm:{
					id:0,
					sensor_name: '',
					show_type: 1,
					save_type: 2, //1存储，2不存储，3变化存储
					data_key: '',
					magnification: 1,
					value_offset: 0,
					threshold: 1,
					unit: '',
					report_type: 0,
					decimals: 0,
					list_order: '',
					icon: 'static/images/icon/icon1.png',
					is_virtual:1,
					formula:''
				},
                addFormVisible: false,
				editFormVisible: false,
				oneUpdateVisible:false,
				formulaVisible:false,
				formulaInfoVisible:false,
                baseurl: this.$baseurl,
                close: false,
                loading:false,
                only: false,
                id: null,
                num: 600,
                formLabelWidth2: '2.8rem',
                formLabelWidth: '2.1rem',
                domains: [],
				isExam:false,
				wsUrl:this.$wssUrl,
				Socket:null,
				timer:null,
                //domains2: [],
                domainIndex: 0,
                // dynamicValidateForm: {
                //     domains: []
                // },
                reportTypes: reportTypes,
                saves: saves,
                options: options,
                points:points
            }
        },
		
		watch: {
		   filterText(val) {
			  this.$refs.tree.filter(val);
		   }
		},
		
		// components:{
		// 	FormulaCreater,
		// 	FormulaInfo
		// },
        
		created() {
			//this.id = localStorage.getItem("directDeviceId");
            this.deviceData= JSON.parse(localStorage.getItem("virDeviceData"));
            this.getSensor();
			this.getSlaveSensorTree(this.deviceData.product_id);
        },
        methods: {
			connectSensors() {
				var that = this;
				this.Socket = new WebSocket(this.wsUrl);
				if (this.Socket.readyState != WebSocket.OPEN) {
					this.Socket.onopen = function() {
						var pingData = {
							action: "debug",
							data: {
								equip_id:that.deviceData.id,
								user_id: localStorage.getItem('at_userId'),
								token: localStorage.getItem("attoken")
							} 
						};
			
						that.Socket.send(JSON.stringify(pingData));
						//console.log(that.Socket);
						//readyState常量值的含义：
						//0 (CONNECTING)  正在链接中;
						//1 (OPEN) 已经链接并且可以通讯;
						//2 (CLOSING) 连接正在关闭;
						//3 (CLOSED) 连接已关闭或者没有链接成功;
						if(that.Socket.readyState==1){
							// that.$message({
							// 	message: '数据通道建立成功!',
							// 	type: 'success',
							// 	offset:300,
							// 	duration:2000,
							// 	center: true
							// });   
						}else if(that.Socket.readyState==3){
							that.$message({
								message: '数据通信失败,无法建立连接或连接已关闭!',
								type: 'error',
								offset:300,
								duration:2000,
								center: true
							});
						}
						that.refreshDataAll(that.deviceData.id);
						that.timer = setInterval(function() {
							that.Socket.send(JSON.stringify(pingData));
						}, 30000);
						console.log('连接成功')
					};
				};
				this.Socket.onerror = this.onError;
				this.Socket.onmessage = this.onMessage;
			},
			
			refreshDataAll(id) {
				var that = this;
				this.$http({
					method: 'post',
					url: 'api/equip/refresh',
					data:{
						"id": id,
						"type":3,
						"mode": 'all'
			        } 
				}).then(res => {
					if (res && res.data.result == "success") {
						console.log("数据刷新成功")
					}
				}).catch(error => {
			        console.log(error);
				});
			},
			
			onError(e) {
				var that=this;
				clearInterval(that.timer);
				this.Socket.close(); 
				console.log('连接失败，尝试重连');
				this.connectSensors();
			},
			
			isObject(obj) {
				return obj.constructor.toString().indexOf("Object") > -1;
			},
			onMessage(msg) {
				var that = this;
				var messageData = JSON.parse(msg.data);
				if (messageData.result == "success" && this.isObject(messageData.data)) {
					var liveDatas = messageData.data;
					if (liveDatas.data && liveDatas.equip) {
						for (let i = 0, len = that.domains.length; i < len; i++) {
							for (let key in liveDatas.data) {
								if (that.domains[i].id == key) {
									that.domains[i].value = liveDatas.data[key];
								}
			
							}
						}
					}
				} else {
					console.log(messageData.message);
				}
			},
			
		    examConnect(){
				this.isExam=true;
				this.connectSensors();
			},
			
			// changeVal(item) {
			// 	var that = this;
			// 	this.$prompt('数据点名称:' + '<span style="color:deepskyblue;">' + item.sensor_name + '</span><br/><span style="color:red">如果设备正在使用,请确保该操作没有危险性！</span>','写入测试', {
			// 			confirmButtonText: '确定',
			// 			cancelButtonText: '取消',
			// 			inputPattern: item.show_type == 2?/^-{0,1}\d+(\.\d+)?$/:/^[0|1]$/,
			// 			dangerouslyUseHTMLString: true,
			// 			inputPlaceholder: item.value,
			// 			inputErrorMessage: item.show_type == 2 ? '设值错误，值必须为数字！' : '非数值变量请使用0/1值！'
			// 		}).then(({
			// 		value
			// 	}) => {
			// 		if (value) {
			// 			this.$http({
			// 				method: 'post',
			// 				url: 'api/sensor/write',
			// 				data: {
			// 					"id": item.id,
			// 					"value": value
			
			// 				}
			// 			}).then(res => {
			// 				if (res && res.data.result == "success") {
			
			// 					that.$message({
			// 						message: '写入数据点成功!',
			// 						type: 'success',
			// 						offset:300,
			// 						center: true
			// 					});
			// 				}
			// 				// console.log(that.pointdata[0].icon)
			// 			}).catch(error => {
			// 				console.log(error);
			// 			});
			// 		} else {
			// 			this.$message({
			// 				type: 'error',
			// 				offset:300,
			// 				message: '写入失败，修改值不能为空！',
			// 				center: true
			// 			});
			// 		}
			
			// 	}).catch(() => {
			// 		this.$message({
			// 			type: 'info',
			// 			message: '取消写入!'
			// 		});
			
			// 	});
			// },
			
			cancelConnect(){
				var that=this;
				this.isExam=false;
				for (let i = 0, len = this.domains.length; i < len; i++) {
					this.domains[i].value = '';
				}
				clearInterval(that.timer);
				this.Socket.close();
				console.log('连接已关闭');
			},
			
			addSensor() {
			    var that = this;
				this.oper="add";
				this.addForm.equip_id=this.deviceData.id;
				this.addForm.sensor_name = '';
				this.addForm.data_key = '';
				this.addForm.decimals = this.points[0].value;
				this.drawerShow = false;
				this.addForm.formula="";
				this.addForm.data_key = 'var_1';
				this.addForm.show_type=this.options[0].value;
				this.addForm.threshold=0;
				this.addForm.magnification=1;
				this.addForm.value_offset=0;
				setTimeout(function(){
					that.drawerShow = true;
					that.reSetString();
				},500)
				
				//下面的默认排序号是当前排序号的最大值加1
				if(this.domains.length){
					let max = Number(this.domains[that.domains.length - 1].list_order) || 1;
					for(let i=0,len=this.domains.length;i<len;i++){
						if(Number(this.domains[i].list_order) || Number(this.domains[i].list_order)==0){
						    max = max < Number(this.domains[i].list_order)?Number(this.domains[i].list_order):max;
						}
					}
					this.addForm.list_order=max+1;
				}else{
					this.addForm.list_order = 1;
				}
			    this.addFormVisible = true;
			},
			
			addHappen() {
			    var that = this;
				if(!this.addForm.sensor_name){
					this.$message({
					    message: '数据点名称不能为空!',
					    type: 'error',
						offset:300,
						duration:2000,
					    center: true
					});
					return
				}
				if(!this.addForm.formula){
					this.$message({
					    message: '计算公式不能为空!',
					    type: 'error',
						offset:300,
						duration:2000,
					    center: true
					});
					return
				}
				this.$http({
			        method: 'post',
			        url:'api/sensor/add',
			        data: this.addForm
			    }).then(res => {
			        if (res && res.data.result == "success") {
			            this.$message({
			                message:'恭喜，添加虚拟数据点成功!',
			                type: 'success',
							duration:2000,
							offset:300,
			                center: true
			            });
			            this.getSensor(that.deviceData.id);
					}
			    }).catch(error => {
			        console.log(error);
			
			    });
			    this.addFormVisible = false;
			},
			
			getIndex(ind) {
			    this.domainIndex = ind;
			    this.domains[ind].visible = true;
			    event.stopPropagation();
			},
			
			closePop() {
			    this.domains[this.domainIndex].visible = false;
			},
			
			chooseIcon(i,item) {
			    var that = this;
				this.whichOne="icon";
			    let iconurl = 'static/images/icon/icon' + i + '.png';
				for (var key in this.editForm){
					this.editForm[key]=item[key];
				}
				this.editForm.icon = iconurl;
				item.icon = iconurl;
			    if (item.save_type == '存储') {
					this.editForm.save_type = 1;
				} else if (item.save_type == '不存储') {
					this.editForm.save_type = 2;
				} else if (item.save_type == '变化存储') {
					this.editForm.save_type = 3;
				}
				this.updateSensor();
			},
			
			//获取设备的从机和变量树
			getSlaveSensorTree(id){
				var that = this;
				this.sensorTree = [];
				this.$http({
				    method: 'post',
				    url: 'api/equip/sensorTree',   //该接口已去掉虚拟变量
				    data: {
				        "product_id": id,
					}
				}).then(res => {
				    if (res && res.data.result == "success") {
				        if(res.data.data.length){
						    this.sensorTree=Array.from(res.data.data);
						   
					    }
				    }
				}).catch(error => {
				    console.log(error);
				});
			},
            
            getSensor() {
			    var that = this;
			    this.domains = [];
			    this.$http({
			        method: 'post',
			        url: 'api/sensor/all',
			        data: {
			            "equip_id":this.deviceData.id,
			            "order": 'address'
			
			        }
			    }).then(res => {
			        if (res && res.data.result == "success") {
			            //that.domains = res.data.data.sort(this.sortName('sensor_name'));
			            that.domains = Array.from(res.data.data);
			            let len = that.domains.length;
			            //that.addForm.list_order=Number(that.domains[len-1].list_order)+1;
			            for (let i = 0, len = res.data.data.length; i < len; i++) {
			                that.domains[i] = res.data.data[i];
							that.$set(that.domains[i],'value','');
							//that.$set(that.domains[i],'check',false);
							that.$set(that.domains[i],'visible',false);
							delete that.domains[i].sensor_code;
			                if (res.data.data[i].show_type > 2) {
			                    that.domains[i].decimals = 0;
			                    that.domains[i].unit = '';
			                }
			                
		                    if (res.data.data[i].save_type == 1) {
			                    that.domains[i].save_type = '存储';
			                } else if (res.data.data[i].save_type == 2) {
			                    that.domains[i].save_type = '不存储';
			                } else if (res.data.data[i].save_type == 3) {
			                    that.domains[i].save_type = '变化存储';
			                }
			            }
			        }
			
			    }).catch(error => {
			        console.log(error);
			        this.domains = [];
			    });
			
			},
			
			sureDeleteSensor(item) {
				this.$confirm('删除后无法恢复, 是否确认删除该数据点?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.removeDomain(item);
				}).catch(() => {
	//               this.$message({
	//                   type: 'info',
							// duration:2000,
	//                   message: '已取消删除'
	//               });
				});
		    },
			
			removeDomain(item) {
			    var that = this;
			    this.$http({
			        method: 'post',
			        url: 'api/sensor/delete',
			        data: {
			            "id": item.id
			
			        }
			    }).then(res => {
			        if (res && res.data.result == "success") {
			            this.$message({
			                message: '恭喜,删除虚拟数据点成功!',
			                type: 'success',
							offset:300,
							duration:2000,
			                center: true
			            });
			            this.getSensor(that.deviceData.id);
					}
			    }).catch(error => {
			        console.log(error);
			
			    });
			},
			
			editFormula(item){
				var that=this;
				this.oper="edit";
				this.whichOne = "formula";
				
				for(var key in this.editForm){
					this.editForm[key]=item[key];
				}
				if (item.save_type == '存储') {
					this.editForm.save_type = 1;
				} else if (item.save_type == '不存储') {
					this.editForm.save_type = 2;
				} else if (item.save_type == '变化存储') {
					this.editForm.save_type = 3;
				}
				setTimeout(function(){
					that.drawerShow = true;
					that.reSetString();
				},500)
				this.formulaVisible = true;
			},
			
		    goBack() {
				var that=this;
				clearInterval(that.timer);
				if (this.Socket) {
					this.Socket.close();
					this.Socket.onerror=null;
				}
                this.$router.go(-1);
            },
			
			getSensorInfo(id){
				this.$http({
					method: 'post',
					url: 'api/sensor/info',
					data: {'id':id}
				}).then(res => {
					if (res && res.data.result == "success") {
						for(var key in this.editForm){
							this.editForm[key]=res.data.data[key]
						}
						this.editForm.show_type=Number(res.data.data.show_type);
					}
				}).catch(error => {
					console.log(error);
					
				});
			},
			
			async showUpdate(index, e,id) {
				var that=this;
				this.oper="edit";
				this.drawerShow = false;
				await this.getSensorInfo(id);
				setTimeout(function(){
					that.drawerShow = true;
					that.reSetString();
				},500)
			    this.editFormVisible = true;
            },
			
			async updateOne(index,item,key,text){
				this.whichOne=key;
				this.whatName=item.sensor_name;
				this.whatText=text;
				await this.getSensorInfo(item.id);
				this.oneUpdateVisible = true;
			},
			
            updateSensor() {
                var that = this;
				if(!this.editForm.sensor_name){
					this.$message({
					    message: '数据点名称不能为空!',
					    type: 'error',
						offset:300,
						duration:2000,
					    center: true
					});
					return
				}
				if(!this.editForm.formula){
					this.$message({
					    message: '计算公式不能为空!',
					    type: 'error',
						offset:300,
						duration:2000,
					    center: true
					});
					return
				}
                this.$http({
                    method: 'post',
                    url: 'api/sensor/update',
                    data: this.editForm
                }).then(res => {
                    if (res && res.data.result == "success") {
                        this.$message({
                            message: '恭喜,修改数据点成功!',
                            type: 'success',
                            center: true
                        });
						this.editFormVisible=false;
						this.formulaVisible = false;
						this.oneUpdateVisible = false;
                        this.getSensor();
                    }

                }).catch(error => {
					this.editFormVisible=false;
					this.formulaVisible = false;
					this.oneUpdateVisible = false;
					if(this.whichOne=="icon"){
						this.getSensor();
					}
                    console.log(error)
                });
            },
			
			filterNode(value, data) {
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			
			getSensorString(data,node,ele){
				//console.log(data);
				if(!data.data_key){
					return
				}
				this.reSet = true;
				this.sibling=ele.$el.parentNode.children;
				// for(let i=0;i<this.sibling.length;i++){
				// 	  this.sibling[i].style.color="#333";
				// }
				ele.$el.style.color = "#409eff";
				let str='$product["'+data.equip_code+'"]["devices"]["'+data.slave_no+'"]["variables"]["'+data.data_key+'"]'+'  ';
				if(this.oper=="add"){
					this.addForm.formula=(this.addForm.formula+ '  '+ str).trim();
				}else if(this.oper=="edit"){
					this.editForm.formula=(this.editForm.formula + '  ' + str).trim();
				}
			},
			
			reSetString(){
				this.reSet=false;
				if(this.sibling.length){
					for(let i=0;i<this.sibling.length;i++){
						this.sibling[i].style.color="#333";
					}
				}
			}
        },
		beforeDestroy() {
			if(this.isExam){
			   this.cancelConnect();
			}
		    this.$message.closeAll();
		},
		
		destroyed() {
			var that=this;
		    clearInterval(that.timer);
		    if (this.Socket) {
				this.Socket.close();
				this.Socket.onerror=null;
			}
		
		}

    }
</script>

<style scoped>
    @media all and (max-width:2560px) {
        .virSensorList {
            width:80%!important;
        }
        
        .triBox {
            width: 100%;
            height: 20.1rem!important;
        }
    }
    
    @media all and (max-width:1920px) {
        .virSensorList {
            width:99.4%!important;
        }
       
        .triBox {
            height: 13.5rem!important;
        }
    }
    
    @media all and (max-width:1600px) {
        .virSensorList {
            width:99.4%!important;
        }
        
        .virSensorHead {
            margin-left: 0rem !important;
        }
        
        .block {
            margin-left: -0.4rem!important;
        }
        .inpu_3 {
            width: 4rem!important;
        }
        .sort {
            width: 1.8rem!important;
        }
    }
    
    @media all and (max-width:1366px) {
        .triBox {
            height: 14.1rem!important;
        }
        .sort {
            width: 2.2rem!important;
        }
    }
    
    .inpu_2,
    .inpu_4 {
        display: inline-block;
        width: 2.4rem;
        font-size: 0.25rem;
        vertical-align: top;
        border: 1px solid #ccc;
        border-radius: 5px;
        height: 0.6rem;
        line-height: 0.6rem;
        text-align: center;
		margin:0;
        /* margin-top: -0.2rem; */
    }
    
    .inpu_4 {
        width: 4rem;
        border: 0 !important;
        font-size: 0.35rem;
    }
	
	.inpu_2{
		margin-left:-0.15rem;
	}
    
    .inpu_3 {
        display: inline-block;
        width:4.5rem;
        height: 0.6rem;
        text-align: center;
        line-height: 0.6rem;
        vertical-align: top;
        overflow: visible;
		margin-left:0;
        /* margin-top: -0.2rem; */
    }
    
    .virSensorList {
        width:90%;
        height:auto;
        margin-top: 0.2rem;
        padding: 0;
        text-align: left;
        padding-left: 0.6rem;
		/* border:1px solid red; */
    }
    
   
    .oneSensor,
    .virSensorHead {
        height: 0.8rem;
        line-height: 0.8rem;
        /* border:1px solid red; */
        /* padding-left: 0.2rem; */
        white-space: nowrap;
    }
	
    
    .virSensorHead {
        width: 100%;
        border-bottom: 1px solid #111;
        margin: 0.1rem 0;
		padding-left:0!important;
    }
    
    .btnBox {
		/* display: */
        width: 90%;
        padding-left: 0.6rem;
        text-align: left;
        height:0.9rem;
        line-height: 0.9rem;
        /* border:1px solid red; */
        margin-top:0.1rem;
		/* border:none; */
    }
    
    .oneSensor>>>.el-input__inner {
        padding-left: 4px;
        padding-right: 2px;
    }
    
    .oneSensor>>>.el-select__caret {
        font-size: 12px;
    }
    
    .oneSensor>>>.el-input__icon {
        width: 14px;
    }
   
    .thumb {
        width: 0.8rem;
        height: 0.8rem;
        vertical-align: middle;
    }
    
    .iconbtn {
        width: 0.65rem;
        height: 0.65rem;
        vertical-align: top;
        padding: 0;
        border: none;
		margin-left:0.1rem;
		margin-top:-1px;
		/* border:1px solid blue; */
        /* margin-right: 0.1rem; */
        /* margin-top:-0.2rem; */
    }
    
    .triBox {
		height: 13.5rem;
		overflow: auto;
        width: 100%;
        padding: 0;
		line-height: 0.7rem;
        margin-right: 0;
        padding-top: 0.1rem;
		/* border:1px solid blue; */
    }
    
    .oneSensor {
        display: block;
        margin:0.15rem 0 0 0;
        height: 0.65rem;
        line-height: 0.65rem;
        white-space: nowrap;
		padding-top:1px;
		/* border:1px solid red; */
    }
	
	.oneSensor:hover{
		background-color: #eee;
	}
	
	.oneSensor:first-child{
		margin-top: 0;
	}
    
    .tip {
        display: inline-block;
        width: auto;
        text-align: center;
        color: red;
        font-size: 0.25rem;
        margin-top: 0.2rem;
    }
	
	.formulaBox{
		display:inline-block;
		width:300px;
		border:1px solid #ccc;
		border-radius: 4px;
		font-size:0.3rem;
		vertical-align:top;
		height:0.6rem;
		margin-left:-0.15rem;
		line-height:0.6rem;
		padding-left:4px;
	}
	
	.formulaText{
		float:left;
		width:262px;
		/* width:100%; */
		cursor: pointer;
		/* border:1px solid red; */
		height:100%;
	}
	
	.formulaEdit{
		float:right;
		width:28px;
		/* border:1px solid red; */
		height:100%;
		line-height:0.62rem;
		text-align:center;
	}
	
	.rightBox{
		position:fixed;
		top:0;
		right:0;
		bottom:0;
		z-index:999;
		width:18%;
		box-sizing: border-box;
		opacity:1;
		overflow: auto;
		/* height:100%; */
		padding:0.2rem;
		padding-top:0.1rem;
		background-color: #fff;
		box-shadow:2px 2px 12px #666;
		border-radius:4px 0 0 4px;
		transition:all 500ms linear;
		/* border:1px solid red; */
	}
	
	.zeroWidth{
		box-sizing: border-box;
		width:0!important;
		opacity: 0;
		overflow: hidden;
	}
	
	.rightHead{
		width:100%;
		font-size: 0.3rem;
		font-weight:normal;
		/* font-weight:700; */
		height:0.8rem;
		line-height:0.8rem;
		border-bottom:1px solid #ccc;
		
	}
	
	.sensorTree{
		min-height:1rem;
		/* max-height: calc(100% - 5.6rem); */
		max-height: calc(100% - 1.2rem);
		box-sizing: border-box;
		border-radius:5px;
		margin-top:0.2rem;
		padding-top:0.1rem;
		overflow: auto;
		color:#333;
		border:1px solid #ccc;
	}
	
    .sensorTree /deep/ .el-tree-node__content .el-tree-node__label{
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	
	.sensorTree /deep/ .el-tree-node__content .is-leaf{
		width:0!important;
		height:0!important;
		padding:3px!important;
		overflow: hidden;
		/* padding-left:28px!important; */
	}
	
    .inpu_2 /deep/ .el-input__inner,
	.inpu_3 /deep/ .el-input__inner
	
	{
		padding:0 4px;
		padding-right:0!important;
	}
	
	.editFormula /deep/ .el-textarea__inner,
	.formline_2 /deep/ .el-textarea__inner{
		padding-left:2px;
		padding-right:2px;
	}
	
	.noWrite{
		width:1.6rem!important;
		position:relative;
		border:1px solid deepskyblue;
	}
</style>